<template>
  <div class="page" @click="closeAttr">
    <!--头部-->
    <Header />

    <!--左侧组件列表部分-->
    <Left ref="left" @componentsClick="componentsClick" @placeholder="placeholderFun" />

    <!--内容部份-->
    <div class="xcx-module-container">
      <!-- 控件列表 -->
      <ControlModule :controlList="controlList" />
      <!-- 内容盒子(放置自定义组件的区域) -->
      <div
        class="xcx-module"
        ref="editorWrapper"
        v-loading="name == ''"
        element-loading-text="加载中..."
        @dragover.prevent
        @dragenter="dragenter"
        @dragleave="dragleave"
        @dragover="dragovers"
        @drop="drops"
      >
        <!--组件放置提示-->
        <div class="placeholder" :data-index="0" v-show="placeholder">放在这里</div>
        <!--DIY组件部份-->
        <Module
          :moduleList="moduleList"
          ref="module"
          @moduleClick="moduleClick"
          @moduleMouseovers="moduleMouseovers"
          @moduleMouseout="moduleMouseout"
        />
        <div class="xcx-nomodule" v-if="moduleList.length == 0 && !placeholder">
          <h2>拖动或点击左侧模块进行页面DIY</h2>
        </div>
      </div>

      <!--操作-->
      <ul
        class="xcx-module-option"
        :style="'top:' + optionTop + 'px'"
        @mouseenter="showOption = true"
        @mouseleave="showOption = false"
        v-if="showOption && moduleList.length > 0"
      >
        <li v-if="moduleList.length != 1 && activeIndex != 0" @click="up">
          <el-tooltip effect="dark" content="上移" placement="right">
            <span class="el-icon-top"></span>
          </el-tooltip>
        </li>
        <li @click="moduleList.splice(activeIndex, 1)">
          <el-tooltip effect="dark" content="删除" placement="right">
            <span class="el-icon-close"></span>
          </el-tooltip>
        </li>
        <li @click="copy">
          <el-tooltip effect="dark" content="复制" placement="right">
            <span class="el-icon-document-copy"></span>
          </el-tooltip>
        </li>
        <li v-if="moduleList.length != 1 && activeIndex != moduleList.length - 1" @click="down">
          <el-tooltip effect="dark" content="下移" placement="right">
            <span class="el-icon-bottom"></span>
          </el-tooltip>
        </li>
      </ul>
    </div>

    <!--模块属性-->
    <transition name="right">
      <Attr v-if="showAttr" :attr="curAttrData" />
    </transition>
    <!--控件属性-->
    <transition name="right">
      <ControlAttr v-if="showControlAttr" :attr="ControlAttrData" />
    </transition>
    <!--预览-->
    <transition name="mask">
      <div class="comm-mask" v-if="showPreview"></div>
    </transition>
    <transition name="scale">
      <Preview v-if="showPreview" :moduleList="moduleList" :controlList="controlList" />
    </transition>

    <el-dialog title="为当前版本取名" :visible.sync="saveConfirm" width="30%" center>
      <div
        class="getNameDialog"
        v-loading="saveLoading"
        element-loading-text="保存中..."
        element-loading-spinner="el-icon-loading"
      >
        版本名:
        <el-input
          v-model="curName"
          :placeholder="curUsedName"
          style="width: 200px; margin-left: 20px"
          @keyup.enter.native="save"
        ></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveConfirm = false">取 消</el-button>
        <el-button type="primary" @click="saveAdnUse">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import "../assets/css/diy.scss";
import Header from "@/components/Header.vue";
import Left from "@/components/Left.vue";
import Module from "@/components/Module.vue";
import Attr from "@/components/Attr.vue";
import ControlAttr from "@/components/ControlAttr.vue";
import Preview from "@/views/preview.vue";
import ControlModule from "@/components/ControlModule.vue";
import moduledata from "@/util/module.js";
import defaultPage from "@/util/defaultPage.js";
import { getCurPage, saveAdnUse, getPageById } from "@/api/api.js";
export default {
  components: {
    Header,
    Left,
    Module,
    Attr,
    ControlModule,
    ControlAttr,
    Preview,
  },
  data() {
    return {
      id: "", //页面ID
      name: "", //页面名称
      activeIndex: "", //移上去模块
      selectIndex: "", //选中模块
      placeholder: false, //显示空白区域
      showOption: false, //显示操作按钮
      optionTop: 0, //操作按钮距离顶部
      control: [], //初始化控件
      moduleList: [], //组件列表
      controlList: [], //控件列表
      showAttr: false, //显示模块属性
      showControlAttr: false, //显示控件属性
      curAttrData: [], //当前属性数据
      ControlAttrData: [], //当前控件属性数据
      saveConfirm: false, //保存确认弹窗
      showPreview: false, //显示预览,
      saveLoading: false, //保存loading
      curUsedName: "", //当前正在使用的版本名称
      curName: "", //当前要保存的版本的名称
    };
  },

  created() {
    this.initPage();
  },

  methods: {
    //初始化页面
    async initPage() {
      const { data: { content, name } } = await getCurPage()
      this.moduleList = content?.moduleList || [];
      this.controlList = content?.controlList || [];
      this.name = name;
    },
    async changePage(id, name) {
      const { data: { content } } = await getPageById(id)
      this.moduleList = content?.moduleList || [];
      this.controlList = content?.controlList || [];
      this.name = name;
    },
    //左侧组件点击
    componentsClick(comp, index) {
      let item = JSON.parse(comp);
      this.moduleList.push(item);
      this.$nextTick(() => {
        if (this.$refs.editorWrapper) {
          this.$util.scrollTop(
            this.$refs.editorWrapper,
            this.$refs.editorWrapper.scrollHeight,
            500
          );
        }
      });
    },

    //空白区域
    placeholderFun(flag) {
      this.placeholder = flag;
      this.$refs.module.placeholder = flag;
    },

    //当拖曳元素进入目标元素的时候触发的事件，此事件作用在目标元素上
    dragenter(event) {
      // 拖动到容器的“放到这里（它是个提示）”盒子，就给盒子加上焦点样式
      if (event.target.classList.contains("placeholder")) {
        event.target.classList.add("on");
      }
    },

    //当拖动的元素或文本选择离开有效的放置目标时将触发该事件。此事件作用在目标元素上（具体请看 html5 DataTransfer对象）
    dragleave(event) {
      // 离开目标容器的“放到这里（它是个提示）”盒子，就给盒子移除焦点样式
      if (event.target.classList.contains("placeholder")) {
        event.target.classList.remove("on");
      }
    },

    // 拖拽元素在目标元素上移动的时候触发的事件
    dragovers(event) {
      event.preventDefault();
    },

    // 拖拽组件区域元素的事件drop 被拖拽的元素在目标元素上同时鼠标放开触发的事件
    drops(event) {
      // debugger;
      let moduleIndex = event.dataTransfer.getData("index"); //获取模块索引
      let moduleData = JSON.parse(event.dataTransfer.getData("moduleData")); // 获取模块数据
      moduleData.attrs.index = parseInt(moduleIndex);
      this.placeholder = false;
      if (event.target.classList.contains("placeholder")) {
        event.target.classList.remove("on");
      }
      event.dataTransfer.clearData(); // 清除dragstart事件传递的参数
      if (this.moduleList.length === 0) {
        this.moduleList.push(moduleData);
      } else if (event.target.classList.contains("placeholder")) {
        let index = event.target.getAttribute("data-index");
        this.moduleList.splice(
          index,
          0,
          moduleData
        );
      } else {
      }
    },

    //模块获取焦点，显示操作按钮
    moduleMouseovers(item) {
      this.optionTop = item.top - 100;
      this.showOption = true;
      this.activeIndex = item.index;
    },

    // 容器失去焦点，隐藏按钮区域
    moduleMouseout() {
      this.showOption = false;
    },

    //上移
    up() {
      this.$util.itemUp(this.moduleList, this.activeIndex);
      this.showOption = false;
    },

    //下移
    down() {
      this.$util.itemUp(this.moduleList, this.activeIndex);
      this.showOption = false;
    },

    //复制模块
    copy() {
      console.log(this.moduleList);
      this.moduleList.push({ ...this.moduleList[this.activeIndex] });
    },

    //组件点击
    moduleClick(index) {
      this.selectIndex = index;
      this.showControlAttr = false;
      this.showAttr = true;
      this.curAttrData = this.moduleList[this.selectIndex];
      console.log(this.curAttrData.name, this.curAttrData);
    },
    controlClick(type) {
      this.showAttr = false;
      this.showControlAttr = true;
      console.log(type, this.controlList);
      this.controlList.forEach((res) => {
        if (res.type == type) {
          console.log(res.type, type);
          this.ControlAttrData = res;
        }
      }, this);
    },

    //关闭属性
    closeAttr() {
      this.showControlAttr = false;
      this.showAttr = false;
    },

    //保存
    async saveAdnUse() {
      const that = this;
      if (this.curName == "") return that.$message.error("请输入版本名称");
      this.saveLoading = true;
      let obj = {
        name: this.curName,
        content: {
          controlList: this.controlList,
          moduleList: this.moduleList
        },
      };
      try {
        await saveAdnUse(obj)
        this.saveLoading = false;
        that.$message.success("保存成功");
        this.curName = "";
        his.saveConfirm = false;
      } catch (error) {
        this.saveLoading = false;
        that.$message.error(error);
        this.curName = "";
        his.saveConfirm = false;
      }
    },

    //控件选择
    controlSelect(item) {
      let json = JSON.stringify(item);
      json = JSON.parse(json);
      let findex = this.controlList.findIndex((res) => res.type == json.type);
      if (findex == -1) {
        this.controlList.push(json);
      } else {
        this.controlList.map(function (item) {
          if (item.type == json.type) {
            item.check = json.check;
          }
        });
      }
    },
  },
};
</script>
<style scoped="scoped" lang="scss">
.page {
  height: 100%;
  background: #f1f1f1;
}
/deep/.el-dialog {
  border-radius: 6px;
}
/deep/ .el-loading-spinner {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}
@import "../assets/css/diy.scss";
</style>